package jgl.vajra.management.widget.utils;

import androidx.annotation.NonNull;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by apanda on 2016/12/30.
 */

public class TimerUtils {


    @NonNull
    public static Observable<Integer> countdown(int time) {
        if (time < 0) time = 0;
        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<Long, Integer>() {
                    @Override
                    public Integer apply(Long increaseTime) throws Exception {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1);
    }


    @NonNull
    public static Observable<Long> countdown(long time, TimeUnit _unit) {
        if (time < 0) time = 0;
        final long countTime = time;
        return Observable.interval(0, 1000, _unit)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long increaseTime) throws Exception {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1000, _unit);
    }

    @NonNull
    public static Observable<Long> countdownTime(long time, TimeUnit _unit) {
        if (time < 0) time = 0;
        return Observable.interval(0, 1000, _unit)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .take(time + 1000, _unit);
    }


}
